<template>
  <div class="procurement-analysis">
    <!-- 页面标题 -->
    <PageHeader 
      title="采购分析" 
      description="查看和分析采购数据，包括采购趋势、供应商表现、成本分析等"
      icon="DataAnalysis"
    />
    
    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-value">{{ stats.totalAmount?.toLocaleString() || '0' }}</div>
            <div class="stat-label">总采购金额</div>
            <div class="stat-trend" :class="getTrendClass(stats.amountTrend)">
              <el-icon v-if="stats.amountTrend && stats.amountTrend > 0">
                <Top />
              </el-icon>
              <el-icon v-else-if="stats.amountTrend && stats.amountTrend < 0">
                <Bottom />
              </el-icon>
              {{ Math.abs(stats.amountTrend || 0) }}% 同比
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-value">{{ stats.purchaseCount || '0' }}</div>
            <div class="stat-label">采购订单数</div>
            <div class="stat-trend" :class="getTrendClass(stats.orderTrend)">
              <el-icon v-if="stats.orderTrend && stats.orderTrend > 0">
                <Top />
              </el-icon>
              <el-icon v-else-if="stats.orderTrend && stats.orderTrend < 0">
                <Bottom />
              </el-icon>
              {{ Math.abs(stats.orderTrend || 0) }}% 同比
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-value">{{ stats.supplierCount || '0' }}</div>
            <div class="stat-label">合作供应商</div>
            <div class="stat-trend" :class="getTrendClass(stats.supplierTrend)">
              <el-icon v-if="stats.supplierTrend && stats.supplierTrend > 0">
                <Top />
              </el-icon>
              <el-icon v-else-if="stats.supplierTrend && stats.supplierTrend < 0">
                <Bottom />
              </el-icon>
              {{ Math.abs(stats.supplierTrend || 0) }}% 同比
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-value">{{ stats.avgDeliveryDays || '0' }}</div>
            <div class="stat-label">平均交付天数</div>
            <div class="stat-trend" :class="getTrendClass(-(stats.deliveryTrend || 0))">
              <el-icon v-if="stats.deliveryTrend && stats.deliveryTrend > 0">
                <Top />
              </el-icon>
              <el-icon v-else-if="stats.deliveryTrend && stats.deliveryTrend < 0">
                <Bottom />
              </el-icon>
              {{ Math.abs(stats.deliveryTrend || 0) }}% 同比
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <el-col :span="16">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>采购金额趋势</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="amountTrendChart" class="chart" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>供应商采购占比</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="supplierPieChart" class="chart" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 采购排行榜 -->
    <el-row :gutter="20" class="rankings-section">
      <el-col :span="12">
        <el-card class="ranking-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>采购金额排行榜</span>
            </div>
          </template>
          <el-table :data="topSuppliersByAmount" style="width: 100%">
            <el-table-column type="index" label="#" width="50" />
            <el-table-column prop="name" label="供应商" />
            <el-table-column prop="amount" label="采购金额">
              <template #default="{ row }">
                ¥{{ row.amount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="count" label="订单数" />
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="ranking-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>采购频次排行榜</span>
            </div>
          </template>
          <el-table :data="topSuppliersByFrequency" style="width: 100%">
            <el-table-column type="index" label="#" width="50" />
            <el-table-column prop="name" label="供应商" />
            <el-table-column prop="count" label="采购次数" />
            <el-table-column prop="amount" label="采购金额">
              <template #default="{ row }">
                ¥{{ row.amount.toLocaleString() }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from '@vue/runtime-core'
import { Top, Bottom } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import PageHeader from '@/components/layout/PageHeader.vue'

// 数据模型
interface ProcurementStats {
  totalAmount: number
  purchaseCount: number
  supplierCount: number
  avgDeliveryDays: number
  amountTrend: number
  orderTrend: number
  supplierTrend: number
  deliveryTrend: number
}

interface SupplierRanking {
  id: number
  name: string
  amount: number
  count: number
}

// 响应式数据
const stats = reactive<ProcurementStats>({
  totalAmount: 0,
  purchaseCount: 0,
  supplierCount: 0,
  avgDeliveryDays: 0,
  amountTrend: 0,
  orderTrend: 0,
  supplierTrend: 0,
  deliveryTrend: 0
})

const topSuppliersByAmount = ref<SupplierRanking[]>([])
const topSuppliersByFrequency = ref<SupplierRanking[]>([])

// 图表引用
const amountTrendChart = ref<HTMLDivElement | null>(null)
const supplierPieChart = ref<HTMLDivElement | null>(null)
let amountTrendChartInstance: echarts.ECharts | null = null
let supplierPieChartInstance: echarts.ECharts | null = null

// 获取趋势类名
const getTrendClass = (trend: number | undefined) => {
  if (trend === undefined) return ''
  return trend > 0 ? 'trend-up' : trend < 0 ? 'trend-down' : ''
}

// 加载统计数据
const loadStats = () => {
  // 模拟数据
  stats.totalAmount = 1250000
  stats.purchaseCount = 128
  stats.supplierCount = 24
  stats.avgDeliveryDays = 7.5
  stats.amountTrend = 12.5
  stats.orderTrend = 8.3
  stats.supplierTrend = 5.2
  stats.deliveryTrend = -2.1
}

// 加载供应商排行榜
const loadSupplierRankings = () => {
  // 模拟数据
  topSuppliersByAmount.value = [
    { id: 1, name: '华为技术有限公司', amount: 320000, count: 12 },
    { id: 2, name: '阿里巴巴集团', amount: 280000, count: 8 },
    { id: 3, name: '腾讯科技', amount: 195000, count: 6 },
    { id: 4, name: '小米科技', amount: 168000, count: 10 },
    { id: 5, name: '百度在线网络', amount: 132000, count: 7 }
  ]
  
  topSuppliersByFrequency.value = [
    { id: 1, name: '华为技术有限公司', amount: 320000, count: 12 },
    { id: 2, name: '小米科技', amount: 168000, count: 10 },
    { id: 3, name: '阿里巴巴集团', amount: 280000, count: 8 },
    { id: 4, name: '百度在线网络', amount: 132000, count: 7 },
    { id: 5, name: '腾讯科技', amount: 195000, count: 6 }
  ]
}

// 初始化金额趋势图表
const initAmountTrendChart = () => {
  if (!amountTrendChart.value) return
  
  amountTrendChartInstance = echarts.init(amountTrendChart.value as unknown as HTMLElement)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => `¥${(value / 10000).toFixed(0)}万`
      }
    },
    series: [{
      data: [800000, 950000, 1100000, 1050000, 1200000, 1350000, 1250000, 1400000, 1380000, 1450000, 1520000, 1600000],
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      },
      lineStyle: {
        width: 3
      }
    }]
  }
  
  amountTrendChartInstance.setOption(option)
}

// 初始化供应商饼图
const initSupplierPieChart = () => {
  if (!supplierPieChart.value) return
  
  supplierPieChartInstance = echarts.init(supplierPieChart.value as unknown as HTMLElement)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '0%',
      left: 'center'
    },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 32, name: '华为技术' },
        { value: 28, name: '阿里巴巴' },
        { value: 20, name: '腾讯科技' },
        { value: 12, name: '小米科技' },
        { value: 8, name: '其他' }
      ]
    }]
  }
  
  supplierPieChartInstance.setOption(option)
}

// 窗口大小改变时重置图表
const handleResize = () => {
  if (amountTrendChartInstance) {
    amountTrendChartInstance.resize()
  }
  if (supplierPieChartInstance) {
    supplierPieChartInstance.resize()
  }
}

// 生命周期
onMounted(() => {
  loadStats()
  loadSupplierRankings()
  initAmountTrendChart()
  initSupplierPieChart()
  
  window.addEventListener('resize', handleResize)
})

// 清理事件监听器
// onUnmounted(() => {
//   window.removeEventListener('resize', handleResize)
//   if (amountTrendChartInstance) {
//     amountTrendChartInstance.dispose()
//   }
//   if (supplierPieChartInstance) {
//     supplierPieChartInstance.dispose()
//   }
// })
</script>

<style scoped>
.procurement-analysis {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
}

.stat-content {
  text-align: center;
  padding: 20px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1f2d3d;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.trend-up {
  color: #f5222d;
}

.trend-down {
  color: #52c41a;
}

.charts-section,
.rankings-section {
  margin-bottom: 20px;
}

.chart-card,
.ranking-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  padding: 20px 0;
}

.chart {
  width: 100%;
}
</style>